package xworker.swt.dataObject.bind.values;

import org.xmeta.ActionContext;
import org.xmeta.ActionException;
import org.xmeta.Bindings;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
import xworker.swt.dataObject.bind.Value;
import xworker.lang.actions.code.CodeThingFactory;
import xworker.lang.actions.code.ThingAttribueCode;

public class CodeValue implements Value {
    Thing thing;
    CodeThingFactory codeThingFactory;

    public CodeValue(Thing thing, CodeThingFactory codeThingFactory){
        this.thing = thing;
        this.codeThingFactory = codeThingFactory;
    }

    @Override
    public Object getValue(Object value, DataObject dataObject, ActionContext actionContext) {
        Bindings bindings = actionContext.push();
        try{
            bindings.put("value", value);
            return ThingAttribueCode.execute(thing, "code", codeThingFactory, actionContext);
        }finally {
            actionContext.pop();
        }
    }

    public static CodeValue create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        CodeThingFactory codeThingFactory = self.doAction("getCodeThingFactory", actionContext);
        return new CodeValue(self, codeThingFactory);
    }

    public static CodeThingFactory getCodeThingFactory(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        String language = self.doAction("getLanguage", actionContext);

        switch (language){
            case "groovy":
                return CodeThingFactory.GROOVY;
            case "java":
                return CodeThingFactory.JAVA;
            case "jython":
                return CodeThingFactory.JYTHON;
            case "beanshell":
                return CodeThingFactory.BEANSHELL;
            case "ognl":
                return CodeThingFactory.OGNL;
            case "javascript":
                return CodeThingFactory.JAVASCRIPT;
            case "lua":
                return CodeThingFactory.LUA;
        }

        throw new ActionException("Unknown language " + language + ", path=" + self.getMetadata().getPath());
    }
}
